import React, { Component, PropTypes } from 'react';
import ajax from '../../ajax'

class SelectBox extends Component {

  constructor (props) {
    super(props)

    this.state = {
      data: []
    }

    if ('array' == $.type(this.props.config.data)) {
      this.state.data = this.props.config.data
      this.localType = true
    }

    this.hasInit = false
  }

  static propTypes = {
    config: React.PropTypes.object.isRequired,
    value: React.PropTypes.string
  }

  render() {
    let config = this.props.config

    return (
      <div>
        <select name={config.name} className="form-control" defaultValue={this.props.value} onClick={this.init.bind(this)}>
          {this.state.data.map(item => {
            return <option key={item[config.key || 'id']} value={item[config.key || 'id']}>{item[config.value || 'text']}</option>
          })}
        </select>   
        {!this.localType && <span className="help-block">点击加载数据 新增时请至少选择一次</span>}
      </div>
    )

  }

  init () {
    if (!this.localType && !this.hasInit) {
      this.hasInit = true
      let data = this.props.config.data
      if (data && 'string' === typeof data) {
        ajax({
          url: this.props.config.data
        }, resp => {
          this.setState({
            data: resp.data
          })
        })
      }
    }
  }

}

export default SelectBox

